package com.question.controller

import com.spire.doc.Document
import com.spire.doc.FileFormat
import com.spire.doc.documents.ImageType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.File
import java.io.FileInputStream
import javax.imageio.ImageIO

@RestController
@RequestMapping("trans")
class TransController(
    @Value("\${question.filePath}")
    val path: String,
    @Value("\${question.file}")
    val name: String,
    @Value("\${question.tempPath}")
    val tempPath: String
) {

    private val logger = LoggerFactory.getLogger(javaClass)

    @GetMapping("test")
    fun transTest(): String {
        val sourceFile: File? = File(path, name).let { if (it.exists()) it else null }
        sourceFile ?: return "$path $name source file not found"
        val temp: File = tempPath.let { temp ->
            File(temp).apply { if (!exists()) mkdirs() }
        }
        return try {
            val document = Document().apply { loadFromStream(FileInputStream(sourceFile), FileFormat.Auto) }
            // 只生成第一页
            val image = document.saveToImages(0, ImageType.Bitmap)
            ImageIO.write(image, "PNG", File(temp, "0.png"))
            "success"
        } catch (e: Exception) {
            logger.error("create image file failed:{}", e.message, e)
            "create image file failed."
        }
    }
}